﻿using ControlzEx.Standard;
using GalaSoft.MvvmLight.Messaging;
using KINLO.Data.Reporitory;
using KINLO.DRV.Machine;
using KINLO.MES.MESModels;
using KINLO.Model;
using KINLO.Model.InfoModel;
using KINLO.Model.MES;
using KINLO.UI.Main.Hepler;
using KINLO.UI.Main.MES;
using KINLO.WebApi.MESModels;
using log4net.Repository.Hierarchy;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Interop;
using System.Windows.Markup;

namespace KINLO.UI.Main.Services
{
    public class K20021002CoreService
    {
        #region 字段
        public string Line;
        WeightReporitory DB = new WeightReporitory();
        WeightBakReporitory BDB = new WeightBakReporitory();
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(K20021002CoreService));
        //前扫描器
        public HWScannerMachine FrontScanner;
        //后扫描器
        public HWScannerMachine BackScanner;
        //注液机
        public IVInjMachine InjectionMachine;
        //前电子称
        public List<ElecBalanceMachine> FrontElecBalances;
        //后电子称
        public List<ElecBalanceMachine> BackElecBalances;
        //补液电子称
        public List<ElecBalanceMachine> RepairElecBalances;
        #endregion
        public Counter Count { get; set; }
        System.Timers.Timer timer = new System.Timers.Timer(1000);
        System.Timers.Timer keepActiveTimer = new System.Timers.Timer(1000);
        System.Timers.Timer mescountTimer = new System.Timers.Timer(60000);
        //MESEquipmentMaintainTimer
        System.Timers.Timer mesequipmentmaintaintimer = new System.Timers.Timer(1000);
        System.Timers.Timer Status = new System.Timers.Timer(1000);

        System.Timers.Timer taskStatus = new System.Timers.Timer(1000);
        System.Timers.Timer taskCount_Hour = new System.Timers.Timer(1000);
        System.Timers.Timer taskCount_Day = new System.Timers.Timer(1000);
        System.Timers.Timer taskData = new System.Timers.Timer(1000);
        System.Timers.Timer taskSecondsData = new System.Timers.Timer(1000);
        #region  方法
        public K20021002CoreService(string line, Counter count)
        {
            try
            {
                Count = count;
                Line = line;
                Init();
            }
            catch (Exception ex)
            {
                log.Error(string.Format("初始化发生错误:{0}", ex.Message));
            }
        }
        void Init()
        {

            Messenger.Default.Register<string>(this, "FInjWeight", new Action<string>((s) => CmdFInjectionWeight(s)));
            Messenger.Default.Register<string>(this, "BInjWeight", new Action<string>((s) => CmdBInjectionWeight(s)));
            Messenger.Default.Register<string>(this, "FWeightClear", new Action<string>((s) => CmdBInjectionWeightClear(s)));
            Messenger.Default.Register<string>(this, "BWeightClear", new Action<string>((s) => CmdAInjectionWeightClear(s)));
            //切换班组班次工单前调用产量
            Messenger.Default.Register<string>(this, "UpdateTeamShiftAndWorkOrder", new Action<string>((s) => CmdUpdateTeamShiftAndWorkOrder(s)));
            //切换工单后调用标准参数
            Messenger.Default.Register<string>(this, "CmdUpdateWorkOrder", new Action<string>((s) => CmdUpdateWorkOrder(s)));
            //工单校验
            Messenger.Default.Register<int>(this, "UpdateUserNameCheck", new Action<int>((s) => CmdMESUserNameCheck(s)));

            //关机调用
            //Messenger.Default.Register<int>(this, " CloseCount", new Action<int>((s) => CloseCount(s)));
            Messenger.Default.Register<string>(this, "CloseCount", new Action<string>((s) => CloseCount(s)));


            //timer.Elapsed += Timer_Elapsed;
            //timer.Enabled = true;

            PLCTask();


            if (GlobalValues.InjectionMachine != null)
            {
                InjectionMachine = new IVInjMachine(GlobalValues.InjectionMachine.IP, GlobalValues.InjectionMachine.Port, 200, "注液机", 0);
                //TEST
                InjectionMachine.Start();
                var msg3 = string.Format("注液机:{0},{1} 初始化完成", GlobalValues.InjectionMachine.IP, GlobalValues.InjectionMachine.Port);

                log.Info(msg3);

                //ReceiveEventInfo
                Messenger.Default.Send(msg3, "ReceiveEventInfo");
            }
            if (GlobalValues.FrontElecBalances != null && GlobalValues.FrontElecBalances.Count > 0)
            {
                FrontElecBalances = new List<ElecBalanceMachine>();
                var feb = GlobalValues.FrontElecBalances.OrderBy(s => Convert.ToInt32(s.Name));
                foreach (var f in feb)
                {
                    FrontElecBalances.Add(new ElecBalanceMachine(f.IP, f.Port, f.Name.ToString(), 50, 20));
                    var msg2 = string.Format("前称重电子称:{0},{1} 初始化完成", f.IP, f.Port);
                    log.Info(msg2);
                    Messenger.Default.Send(msg2, "ReceiveEventInfo");
                }
            }
            if (GlobalValues.BackElecBalances != null)
            {
                BackElecBalances = new List<ElecBalanceMachine>();
                var beb = GlobalValues.BackElecBalances.OrderBy(s => Convert.ToInt32(s.Name));
                foreach (var f in beb)
                {
                    BackElecBalances.Add(new ElecBalanceMachine(f.IP, f.Port, f.Name.ToString(), 50, 20));
                    var msg1 = string.Format("后称重电子称:{0},{1} 初始化完成", f.IP, f.Port);
                    log.Info(msg1);
                    Messenger.Default.Send(msg1, "ReceiveEventInfo");
                }
            }


            var msg = "初始化完成 ";
            log.Info(msg);
            Messenger.Default.Send(msg, "ReceiveEventInfo");
            //keepActiveTimer.Elapsed += KeepActiveTimer_Elapsed;
            //keepActiveTimer.Enabled = true;

            KeepActiveTimer();

          
            //补录
            new MESEntryDataService();
            MESinit();
            _taskToken.Cancel();
            //加压杠数据采集
            //PressureChart_Start();


            //mescountTimer.Elapsed += MEScountTimer_Elapsed;
            //mescountTimer.Enabled = true;
            //mesequipmentmaintaintimer.Elapsed += MESEquipmentMaintainTimer_Elapsed;
            //mesequipmentmaintaintimer.Enabled = true;

            //Status.Elapsed += Status_Elapsed;
            //Status.Enabled = true;


        }

        private void MESinit()
        {

            var tip = Count == null ? ".." : ".";
            var msg1 = $"启动MES监控中{Count}";
            //if(Count==null)
            //{
            //    Count = Counter.Load();
            //}

            log.Info(msg1);
            Messenger.Default.Send(msg1, "ReceiveEventInfo");
            //InfoDataModel.Tmp.Load();
            if (!InfoDataModel.Tmp.EnbleMesOnOff)
            {
                return;
            }

            if (InfoDataModel.Tmp.last_StatusData == null)
            {
                InfoDataModel.Tmp.last_StatusData = new Dictionary<int, List<MESEquipmentStatusModel>>();
            }

            //小时生产统计，固定每小时
            taskCount_Hour = new System.Timers.Timer(3600000);

            //taskCount_Hour = new System.Timers.Timer(2000);

            //天生产统计间隔上传，可配置间隔时间
            taskCount_Day = new System.Timers.Timer(Convert.ToInt32(InfoDataModel.Tmp.Url10Time) * 1000);
            //taskCount_Day = new System.Timers.Timer(2000);
            //taskCount_Day = new System.Timers.Timer(28800);
            //工艺参数间隔上传，可配置间隔时间
            //taskData = new System.Timers.Timer(Convert.ToInt32(InfoDataModel.Tmp.Url9Time) * 1000);
            //标准参数接口
            taskSecondsData = new System.Timers.Timer(Convert.ToInt32(InfoDataModel.Tmp.Url4Time) * 1000);
            //taskSecondsData = new System.Timers.Timer(1800);

            taskCount_Hour.Elapsed += TaskCountHour_Elapsed;
            taskCount_Day.Elapsed += TaskCountDay_Elapsed;
            taskSecondsData.Elapsed += TaskSecondsData_Elapsed;


            taskCount_Hour.Enabled = true;
            taskCount_Day.Enabled = true;
            taskSecondsData.Enabled = true;

            //设备状态
            taskStatus = new System.Timers.Timer(1000);
            taskStatus.Elapsed += TaskStatus_Elapsed;
            taskStatus.Enabled = true;

            var msg2 = "启动MES监控成功 ";
            log.Info(msg2);
            Messenger.Default.Send(msg2, "ReceiveEventInfo");

        }
        object frontLock = new object();
        object backLock = new object();
    
        object mescountLock = new object();

        #region MES
        /// <summary>
        /// 切换班组班次 OR 切换工单调用产量上传接口
        /// </summary>
        /// <param name="a"></param>
        private void CmdUpdateTeamShiftAndWorkOrder(string a)
        {
            try
            {
                if (InfoDataModel.Tmp.EnbleMesOnOff)
                {
                    CountModel countModel = new CountModel();
                    
                    countModel.InCount = Count.INCount;
                    countModel.OkCount = Count.OKCount;
                    countModel.NgCount = Count.NGCount;
                    var hourResult = InjectMes.MESCountUpLoad_Hour(countModel);
                    var dayResult = InjectMes.MESCountUpLoad_Day(countModel);
                    //全部调用成功则产量清零操作
                    if (dayResult == 1 && hourResult == 1)
                    {
                        //产量清零操作
                        Count.ClearZero();
                        log.Info($"产量清零】切换工单班组班次产量清零");
                    }
                    else
                    {
                        log.Info($"产量清零】切换工单班组班次清零失败，生产统计天{dayResult.ToString()} 或者小时{hourResult.ToString()}接口调用失败{DateTime.Now.ToString()}:");
                    }
                }
            }catch (Exception ex)
            {
                log.Info($"切换工单班组班次产量清零失败{ex.ToString()}");
            }
          
        }
        /// <summary>
        /// 切换工单调用标准参数接口
        /// </summary>
        /// <param name="a"></param>
        private void CmdUpdateWorkOrder(string a)
        {
            try
            {
                if (InfoDataModel.Tmp.EnbleMesOnOff)
                {            
                    PumDataSave();
                }
            }catch (Exception e)
            {
                //log.Info();
            }
          
        }

        /// <summary>
        /// 工单校验成功调用
        /// </summary>
        private void CmdMESUserNameCheck(int result)
        {
            try
            {
                for (int i = 0; i < 3; i++)
                {
                    InjectionMachine.PLC.WriteSingleRegister(30542, 1);
                }
            }catch(Exception e)
            {
                log.Info("工单校验成功写入PLC失败");
            }



        }

        object lockSaveObject = new object();

        /// <summary>
        /// 设备状态
        /// </summary>
        /// <param name="state"></param>
        //private void TaskStatus_Elapsed(object state)
        private void TaskStatus_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            Task.Run(() =>
            {
                try
                {
                    string reason = "";
                    string code = "";
                    string Rcode = "";
                    int Alarm = 0;
                    int Auto = 0;
                    int Stop = 0;
                    int Maintain = 0;
                    int _recode = 0;

                    //设备状态 0:报警、1:未归位、2:已归位、3:手动中 4:待机中 5:运行中 7:故障
                    var autoMaintainLst = InjectionMachine.PLC.ReadHoldingRegisters(30540, 1);

                    //收到空，说明设备不在线
                    if (autoMaintainLst == null)
                    {
                        //lock (lockSaveObject)
                        //{
                        //    InfoDataModel.Tmp.status = "6";
                        //    InfoDataModel.Tmp.Save();
                        //}
                        //InfoDataModel.Tmp.status = "6";
                        //InfoDataModel.Tmp.Save();
                        return;
                    }
                    //设备状态 0:待机、1:运行、2:故障、3:报警(运行,停止,报警)
                    int status = 0;
                    switch (autoMaintainLst[0])
                    {
                        case 0:
                            status = 3; break;
                        case 1:
                        case 2:
                        case 4:
                        case 6:
                            status = 0; break;
                        case 5:
                            status = 1; break;
                        case 7:
                            status = 2; break;
                    }

                    //上次设备状态
                    int last_status = int.Parse((InfoDataModel.Tmp.status==null|| InfoDataModel.Tmp.status =="6")? "0": InfoDataModel.Tmp.status);
                    if (status != last_status)
                    {
                        var msg1 = $"设备状态切换MES调用{last_status.ToString()}=>{status.ToString()}";
                        log.Info(msg1);
                        Messenger.Default.Send(msg1, "ReceiveEventInfo");

                        Dictionary<int, List<MESEquipmentStatusModel>> mesEquipmentStatusData = new Dictionary<int, List<MESEquipmentStatusModel>>();
                        mesEquipmentStatusData.Add(status, new List<MESEquipmentStatusModel>());
                        //if (status == 0)
                        //{
                        //    last_StSeconds = DateTime.Now;
                        //}
                        if (status == 3)
                        {
                            //报警原因编码
                            var alarmInfosClass = AlarmInfosData.Instance;
                            var alarmInfosData = alarmInfosClass.GetData();

                            var filteredAlarmInfosData = alarmInfosData
                                   .Where(pair => pair.Key.Contains("注液机"))
                                  .Select(pair => pair.Value)
                                    .ToList();
                            if (filteredAlarmInfosData != null && filteredAlarmInfosData.Count > 0)
                            {
                              
                                foreach (var alarmInfo in filteredAlarmInfosData[0])
                                {
                                    string deviceType = alarmInfo.DeviceType;
                                    string alarmAddress = alarmInfo.AlarmAddress;
                                    string alarmContent = alarmInfo.AlarmContent;
                                    var alarmcondition = alarmInfo.Alarmcondition;

                                    //是否当前代码报警
                                    bool isalarmsta = false;

                                    // 如果输入为空或只有一个字符，直接返回"0"
                                    if (string.IsNullOrEmpty(alarmAddress) || alarmAddress.Length == 1)
                                    {
                                        isalarmsta = false;
                                    }
                                    else
                                    {
                                        //获取最后一个数字
                                        int num = int.Parse(alarmAddress[alarmAddress.Length - 1].ToString());
                                        alarmAddress = alarmAddress.Replace("MX", "");
                                        //索引
                                        int indexAlarm = 0;
                                        // 去掉输入字符串的最后一个位，剩下的就是MB字节地址
                                        alarmAddress = alarmAddress.Substring(0, alarmAddress.Length - 1);

                                        //是否可以除以2得到了整数结果，如果是则是前八位，不是则是后八位
                                        if (int.Parse(alarmAddress) % 2 == 0)
                                        {
                                            indexAlarm = num;
                                        }
                                        else
                                        {
                                            indexAlarm = num + 8;
                                        }



                                        // 将剩余部分解析为整数，除以2，然后转换为字符串，MB地址除2取整就等于MW字地址
                                        int value = int.Parse(alarmAddress);
                                        int dividedValue = value / 2;
                                        var alarmValue = InjectionMachine.PLC.ReadHoldingRegisters((ushort)dividedValue, 1);
                                        //将结果转成16位二进制，一位代表一个报警地址，一个MW字有两个MB字节，一个MB地址有8个MX位，所以一个MW就有16位   3
                                        string alarmStr = Convert.ToString(alarmValue[0], 2).PadLeft(16, '0');
                                        if (int.Parse(alarmStr[15 - indexAlarm].ToString()) == alarmcondition)
                                        {
                                            isalarmsta = true;
                                        }
                                    }

                                    if (isalarmsta)
                                    {
                                        mesEquipmentStatusData[status].Add(new MESEquipmentStatusModel()
                                        {
                                            EquipmentCode = InfoDataModel.Tmp.EquipmentCode,
                                            State_Code = status.ToString(),
                                            St_seconds = "",
                                            St_ResonCode = "",
                                            Alarm_ResonCode = alarmInfo.Id.ToString(),
                                            Alarm_ResonName = alarmInfo.AlarmContent,

                                            Beg_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                            End_time = ""
                                            //End_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                        });
                                    }

                                }
                            }
                            else
                            {
                                code = "001";
                                reason = "报警";
                            }
                        }
                        //如果没有检测到是哪个报警，则没有更新报警地址
                        if (status == 3 && mesEquipmentStatusData[status].Count == 0)
                        {
                            mesEquipmentStatusData[status].Add(
                                                new MESEquipmentStatusModel()
                                                {
                                                    EquipmentCode = InfoDataModel.Tmp.EquipmentCode,
                                                    State_Code = status.ToString(),
                                                    St_seconds = "",
                                                    St_ResonCode = "",
                                                    Alarm_ResonCode = "66666",
                                                    Alarm_ResonName = "报警",
                                                    Beg_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                                    End_time = ""
                                                }
                                            );
                        }
                        //故障报修调用接口
                        if (status == 2)
                        {
                            if (InfoDataModel.Tmp.EnbleMesOnOff)
                            {
                                var result = InjectMes.MESEquipmentMaintain();
                                if (result == 1)
                                {
                                    //lock (lockSaveObject)
                                    //{
                                    //    InfoDataModel.Tmp.status = status.ToString();
                                    //    InfoDataModel.Tmp.Save();
                                    //}
                                    InfoDataModel.Tmp.status = status.ToString();
                                    //InfoDataModel.Tmp.Save();
                                }
                            }

                            return;
                        }

                        if (status == 1 || status == 0)
                        {
                            mesEquipmentStatusData[status].Add(
                                new MESEquipmentStatusModel()
                                {
                                    EquipmentCode = InfoDataModel.Tmp.EquipmentCode,
                                    State_Code = status.ToString(),
                                    St_ResonCode = "0",
                                    St_seconds = "0",
                                    Alarm_ResonCode = "",
                                    Alarm_ResonName = "",
                                    Beg_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                    End_time =""
                                }
                             );
                        }
                        //待机时间
                        int secondsDifference = 0;
                        //切换状态传当前的状态信息给MES
                        if (InfoDataModel.Tmp.EnbleMesOnOff)
                        {

                            if (InfoDataModel.Tmp.last_StatusData.TryGetValue(InfoDataModel.Tmp.last_StatusData.Keys.FirstOrDefault(), out List<MESEquipmentStatusModel> firstList))
                            {
                                //上次状态是否待机
                                bool isLast_Status = InfoDataModel.Tmp.last_StatusData.ContainsKey(0);
                                if (isLast_Status)
                                {
                                    //待机原因编码
                                    var _recodeLst = InjectionMachine.PLC.ReadHoldingRegisters(30544, 1);
                                    //判断是否选中了待机原因，选了就更新上次待机原因
                                    if (_recodeLst != null && _recodeLst[0] != 15)
                                    {
                                        //for (int i = 0, j = 1; i <= 10; i++)
                                        //{
                                        //    if (_recodeLst[0] == j)
                                        //    {
                                        //        _recode = i;
                                        //    }
                                        //    j = j * 2;
                                        //}
                                        _recode = _recodeLst[0] - 1;
                                        //保存待机原因编码
                                        InfoDataModel.Tmp.last_recode = _recode;
                                        InjectionMachine.PLC.WriteSingleRegister(30544, 15);
                                    }
                                    else
                                    {
                                        _recode = 0;
                                    }
                                }
                                DateTime begTime;

                                //结束时间减去开始时间算出秒
                                DateTime dateTime1 = DateTime.TryParse(firstList[0].Beg_time, out begTime) ? begTime : DateTime.Now; ;
                                DateTime dateTime2 = DateTime.Now;
                                TimeSpan timeDifference = dateTime2 - dateTime1;
                                secondsDifference = (int)timeDifference.TotalSeconds;
                                firstList.ForEach(x =>
                                {
                                    x.End_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                    x.St_seconds = secondsDifference.ToString();
                                    x.St_ResonCode = isLast_Status ? InfoDataModel.Tmp.last_recode.ToString() : "";
                                });

                                firstList.AddRange(mesEquipmentStatusData[status]);

                               int result= InjectMes.MESEquipmentStatus(firstList);

                                if (result != 1)
                                {
                                    Messenger.Default.Send(firstList, "EquipmentStatus");

                                   
                                }

                            }
                            //清空上次状态信息
                            InfoDataModel.Tmp.last_StatusData.Clear();
                            //保存当前状态，留下次用
                            InfoDataModel.Tmp.last_StatusData.Add(status, new List<MESEquipmentStatusModel>(mesEquipmentStatusData[status]));
                            InfoDataModel.Tmp.status = status.ToString();
                            //InfoDataModel.Tmp.Save();

                        }

                        var msg2 = "设备状态切换MES调用成功";
                        log.Info(msg2);
                        Messenger.Default.Send(msg2, "ReceiveEventInfo");
                    }
                    //log.Info($"【设备状态定时任务正常】");
                }
                catch (Exception ex)
                {
                    var msg = $"【设备状态定时任务异常】:{ex.ToString()}";
                    log.Error(msg);
                    Messenger.Default.Send(msg, "ReceiveEventInfo");
                    
                }
            });
        }
        object lockTaskCountHour = new object();
        /// <summary>
        /// 生产统计上传 小时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TaskCountHour_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {

            Task.Run(() =>
            {
                try
                {
                    var msg1 = $"生产统计小时开始调用";
                    log.Info(msg1);
                    Messenger.Default.Send(msg1, "ReceiveEventInfo");
                    CountModel countModel = new CountModel();
                    countModel.InCount = Count.INCount;
                    countModel.OkCount = Count.OKCount;
                    countModel.NgCount = Count.NGCount;
                    if (InfoDataModel.Tmp.EnbleMesOnOff)
                    {
                        InjectMes.MESCountUpLoad_Hour(countModel);
                    }
                    var msg2= $"生产统计小时调用成功";
                    log.Info(msg2);
                }
                catch (Exception ex)
                {
                    throw;
                }
            });

        }

        object lockTaskCountDay = new object();
        /// <summary>
        /// <summary>
        /// 生产统计上传 天
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TaskCountDay_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {

            Task.Run(() =>
            {
                try
                {
                    CountModel countModel = new CountModel();
                    countModel.InCount = Count.INCount;
                    countModel.OkCount = Count.OKCount;
                    countModel.NgCount = Count.NGCount;
                    if (InfoDataModel.Tmp.EnbleMesOnOff)
                    {
                        InjectMes.MESCountUpLoad_Day(countModel);
                    }
                }
                catch (Exception ex)
                {
                    throw;
                }
            });
        }


        

        /// <summary>
        /// 定时获取标准参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TaskSecondsData_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                PumDataSave();
            }
            catch (Exception ex)
            {

            }

        }

        object PumDataLock = new object();
        /// <summary>
        /// 标准工艺参数获取更新保存方法
        /// </summary>
        public void PumDataSave()
        {
            try
            {
                lock(PumDataLock)
                {
                    var msg1 = $"获取标准参数接口调用";
                    log.Info(msg1);
                    Messenger.Default.Send(msg1, "ReceiveEventInfo");
                    var data = InjectMes.MESSecondsData();
                    if (data != null)
                    {
                        InfoDataModel.Tmp.GeneralData = data;
                    }
                    var msg2 = $"获取标准参数接口调用成功";
                    log.Info(msg1);
                    Messenger.Default.Send(msg2, "ReceiveEventInfo");
                }
                
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 关机调用生产统计上传 小时和 生产统计上传 天接口，然后产量清零
        /// </summary>
        private void CloseCount(string s)
        {

            try
            {
                var msg1 = $"{s}调用接口上传产量启动";
                log.Info(msg1);
                Messenger.Default.Send(msg1, "ReceiveEventInfo");
                CountModel countModel = new CountModel();
                if(Count.INCount==0&&Count.OUTCount==0)
                {
                    log.Info($"{s}调用接口】产量已经清零，已经调用过接口，返回==>");
                    return;
                }
                countModel.InCount = Count.INCount;
                countModel.OkCount = Count.OKCount;
                countModel.NgCount = Count.NGCount;
                if (InfoDataModel.Tmp.EnbleMesOnOff)
                {
                    InjectMes.MESCountUpLoad_Day(countModel);
                    InjectMes.MESCountUpLoad_Hour(countModel);
                    

                    log.Info($"{s}调用接口然后产量清零】");
                }
                else
                {
                    log.Info($"{s}MES关闭】");
                }
                Count.ClearZero();
                InfoDataModel.Tmp.Save();
            }
            catch (Exception ex)
            {
                log.Info($"{s}调用接口然后产量清零】异常{ex}");
            }
        }


        //private void MEScountTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        //{
        //    Task.Run(() =>
        //    {
        //        try
        //        {
        //            if (Monitor.TryEnter(mescountLock))
        //            {
        //                if (InfoDataModel.Tmp.EnbleMesOnOff)
        //                {
        //                    CountModel Counter = new CountModel();
        //                    Counter.InCount = Count.INCount;
        //                    Counter.OkCount = Count.OKCount;
        //                    Counter.NgCount = Count.NGCount;
        //                    var mescountreult = InjectMes.MESCountUpLoad(Counter);
        //                    var msgmes = string.Format($"MES生产统计上传:{(mescountreult == 1 ? "成功" : "失败")}");
        //                    Messenger.Default.Send(msgmes, "ReceiveEventInfo");
        //                    log.Info(msgmes);
        //                }
        //            }
        //        }
        //        catch (Exception)
        //        {

        //        }
        //        finally
        //        {
        //            Monitor.Exit(mescountLock);
        //        }
        //    });
        //}
        //object mesmaintainLock = new object();


        //private void MESEquipmentMaintainTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        //{
        //    Task.Run(() =>
        //    {
        //        try
        //        {
        //            if (Monitor.TryEnter(mesmaintainLock))
        //            {
        //                if (InfoDataModel.Tmp.EnbleMesOnOff)
        //                {
        //                    var mescountreult = InjectMes.MESEquipmentMaintain();
        //                    var msgmes = string.Format($"MES设备报修上传:{(mescountreult == 1 ? "成功" : "失败")}");
        //                    Messenger.Default.Send(msgmes, "ReceiveEventInfo");
        //                    log.Info(msgmes);
        //                }
        //            }
        //        }
        //        catch (Exception)
        //        {

        //        }
        //        finally
        //        {
        //            Monitor.Exit(mesmaintainLock);
        //        }
        //    });
        //}
        //public void MESEquipmentMaintain()
        //{
        //    Task.Run(() =>
        //    {
        //        try
        //        {
        //            if (InfoDataModel.Tmp.EnbleMesOnOff)
        //            {
        //                var mescountreult = InjectMes.MESEquipmentMaintain();
        //                var msgmes = string.Format($"MES设备报修上传:{(mescountreult == 1 ? "成功" : "失败")}");
        //                Messenger.Default.Send(msgmes, "ReceiveEventInfo");
        //                log.Info(msgmes);
        //            }


        //        }
        //        catch (Exception)
        //        {

        //        }

        //    });
        //}

        #endregion

        private CancellationTokenSource _taskToken { get; set; } = new CancellationTokenSource();

        public void PressureChart_Close()
        {
            _taskToken.Cancel();
            log.Info($"停止加压杠曲线图");
        }
        /// <summary>
        /// 每秒获取压力值
        /// </summary>
        public void PressureChart_Start()
        {
            log.Info($"开始启动加压杠曲线图");
            if (_taskToken.Token.IsCancellationRequested) { _taskToken = new CancellationTokenSource(); }
            Task.Factory.StartNew(() =>
            {
                while (!_taskToken.Token.IsCancellationRequested)
                {
                    try
                    {
                        var data = InjectionMachine.ReadPressureChart();

                        //Random random = new Random();
                        //// 创建一个 double 数组
                        //double[] data = new double[4];
                        //// 循环给数组赋随机数值
                        //for (int i = 0; i < data.Length; i++)
                        //{
                        //    //  -90 到 800 之间
                        //    double randomValue = random.NextDouble() * (800 - (-90)) + (-90);
                        //    data[i] = randomValue;
                        //}

                        if (data != null)
                        {
                            DateTime _newtime = DateTime.Now;

                            List<PressureVesselModel> pressureVesselsData = new List<PressureVesselModel>();
                            int i = 1;
                            foreach (var item in data)
                            {
                                string indexName = i.ToString();
                                string _Name = "罐" + i.ToString();

                                pressureVesselsData.Add(new PressureVesselModel
                                {
                                    PressureValue = item,
                                    TimeStamp = _newtime,
                                    Name = _Name,
                                    Type = indexName
                                });
                                i++;
                            }
                            Messenger.Default.Send(pressureVesselsData, "AddPressureChart");
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Info($"【获取加压缸压力错误】{ex.ToString()}");
                    }
                    finally
                    {


                        Thread.Sleep(1000);

                    }
                }


            }, TaskCreationOptions.LongRunning);
        }


        private void KeepActiveTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                if (Monitor.TryEnter(frontLock))
                {
                    Task.Run(() => {
                        ushort[] WeightBits = { 0, 0 };
                        if (FrontElecBalances.Count > 0)
                        {
                            for (var i = 0; i < FrontElecBalances.Count; i++)
                            {
                                if (FrontElecBalances[i].IsConnected)
                                {
                                    if (i < 16)
                                    {
                                        WeightBits[0] += (ushort)Math.Pow(2, i % 16);
                                    }
                                    else
                                    {
                                        WeightBits[1] += (ushort)Math.Pow(2, i % 16);
                                    }
                                }
                            }
                            InjectionMachine.WriteFrontWeightOnline(WeightBits);
                        }
                    });
                }
            }
            finally
            {
                Monitor.Exit(frontLock);
            }
            try
            {
                if (Monitor.TryEnter(backLock))
                {
                    Task.Run(() => {
                        ushort[] WeightBits = { 0, 0 };
                        if (BackElecBalances.Count > 0)
                        {
                            for (var i = 0; i < BackElecBalances.Count; i++)
                            {
                                if (BackElecBalances[i].IsConnected)
                                {
                                    if (i < 16)
                                    {
                                        WeightBits[0] += (ushort)Math.Pow(2, i % 16);
                                    }
                                    else
                                    {
                                        WeightBits[1] += (ushort)Math.Pow(2, i % 16);
                                    }
                                }
                            }
                            InjectionMachine.WriteBackWeightOnline(WeightBits);
                        }
                    });
                }
            }
            finally
            {
                Monitor.Exit(backLock);
            }
        }
        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            //Task.Run(() =>
            //{
                try
                {
                    //var autoMaintainLst666 = InjectionMachine.PLC.ReadHoldingRegisters3(103, 14);
                    //var alarmCode = InjectionMachine.PLC.ReadCoils(1006, 16);
                    ////if (alarmCode[0] == 1)
                    //var alarmCode11 = InjectionMachine.PLC.ReadHoldingRegisters(30540, 1);
                    if (InjectionMachine != null)
                    {

                        if (InjectionMachine.IsConnected)
                            InjectionMachine.WriteKeepActive();
                        Messenger.Default.Send(InjectionMachine.IsConnected, "InjectionStatus");
                    }
                }
                catch (Exception ex)
                {
                     log.Info($"【给PLC在线信号报错】{ex.ToString()}");
                }
            //});
          
        }

        /// <summary>
        /// 前称重、后称重在线信号
        /// </summary>
        private void KeepActiveTimer()
        {
            //前称在线信号
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    try
                    {
                        Thread.Sleep(1000);
                        ushort[] WeightBits = { 0, 0 };
                        if (FrontElecBalances.Count > 0)
                        {
                            for (var i = 0; i < FrontElecBalances.Count; i++)
                            {
                                if (FrontElecBalances[i].IsConnected)
                                {
                                    if (i < 16)
                                    {
                                        WeightBits[0] += (ushort)Math.Pow(2, i % 16);
                                    }
                                    else
                                    {
                                        WeightBits[1] += (ushort)Math.Pow(2, i % 16);
                                    }
                                }
                            }
                            InjectionMachine.WriteFrontWeightOnline(WeightBits);
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Info($"【给前称在线信号报错】{ex.ToString()}");
                        Thread.Sleep(1000);
                    }
                }
   
              
            }, TaskCreationOptions.LongRunning);

            //后称在线信号
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    try
                    {
                        Thread.Sleep(1000);
                        ushort[] WeightBits = { 0, 0 };
                        if (BackElecBalances.Count > 0)
                        {
                            for (var i = 0; i < BackElecBalances.Count; i++)
                            {
                                if (BackElecBalances[i].IsConnected)
                                {
                                    if (i < 16)
                                    {
                                        WeightBits[0] += (ushort)Math.Pow(2, i % 16);
                                    }
                                    else
                                    {
                                        WeightBits[1] += (ushort)Math.Pow(2, i % 16);
                                    }
                                }
                            }
                            InjectionMachine.WriteBackWeightOnline(WeightBits);
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Info($"【给后称在线信号报错】{ex.ToString()}");
                        Thread.Sleep(1000);
                    }
                }

            }, TaskCreationOptions.LongRunning);

           
        }

        private void PLCTask()
        {
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    try
                    {
                        //var autoMaintainLst666 = InjectionMachine.PLC.ReadHoldingRegisters3(103, 14);
                        //var alarmCode = InjectionMachine.PLC.ReadCoils(1006, 16);
                        ////if (alarmCode[0] == 1)
                        //var alarmCode11 = InjectionMachine.PLC.ReadHoldingRegisters(30540, 1);
                        if (InjectionMachine != null)
                        {

                            if (InjectionMachine.IsConnected)
                                InjectionMachine.WriteKeepActive();
                            Messenger.Default.Send(InjectionMachine.IsConnected, "InjectionStatus");
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Info($"【给PLC在线信号报错】{ex.ToString()}");
                    }
                    finally { Thread.Sleep(1000); }
                }

            }, TaskCreationOptions.LongRunning);

        }


        /// <summary>
        /// 注液前称重
        /// </summary>
        /// <param name="s"></param>
        void CmdFInjectionWeight(string s)
        {
            var results = new ushort[] { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 };// 1 有电池OK 2NG重量不在范围  3空电池 
            var trayNum = InjectionMachine.MW304;//前称重托架号6
            var trayRow = InjectionMachine.MW305; //前称重托架行号
            try
            {
                var mgs1 = string.Format("注液前托架号:{0} 行号:{1}", trayNum, trayRow);
                log.Info(mgs1);
                Messenger.Default.Send(mgs1, "ReceiveEventInfo");
                DB.UpdateTrayNoStatus(trayNum.ToString(), trayRow.ToString());
                if (FrontElecBalances.Count > 0)
                {
                    for (var i = 0; i < FrontElecBalances.Count; i++)
                    {
                        FrontElecBalances[i].startIndex = i;
                        FrontElecBalances[i].IsWeightFin = false;
                        FrontElecBalances[i].Weight = 0;
                        FrontElecBalances[i].CurrWeight = 0;
                        FrontElecBalances[i].IsRunning = false;
                        FrontElecBalances[i].ServiceControl(true);
                    }
                    Thread.Sleep(700);
                    var sw = new Stopwatch();
                    sw.Start();
                    while (true)//等待称重完成或超时
                    {
                        if (FrontElecBalances.Where(ss => ss.IsRunning && ss.IsWeightFin == false).ToList().Count > 0)
                        {
                            foreach (var f in FrontElecBalances)
                            {
                                if (sw.ElapsedMilliseconds > GlobalValues.WeightTimeout * 1000)
                                {
                                    sw.Stop();
                                    f.Weight = f.CurrWeight;
                                    if (f.IsRunning == true && f.IsWeightFin == false)
                                    {
                                        var msg = string.Format("【前称重】{0}号称超时", f.startIndex);
                                        Messenger.Default.Send(msg, "ReceiveEventInfo");
                                        log.Error(msg);
                                    }
                                    f.IsWeightFin = true;
                                }
                                log.Info(String.Format("前称重>>> {0} {1} {2}", f.startIndex, f.Weight, f.CurrWeight));
                                f.Weight = f.CurrWeight;
                            }
                            Thread.Sleep(50);
                        }
                        else
                        {
                            foreach (var f in FrontElecBalances)
                            {
                                f.Weight = f.CurrWeight;
                                log.Info(String.Format("前称重>>> {0} {1} {2}", f.startIndex, f.Weight, f.CurrWeight));
                            }
                            break;
                        }
                    }
                    var sb = new StringBuilder();
                    var max = GlobalValues.WeightWave2 + GlobalValues.WeightRef2;
                    var min = GlobalValues.WeightWave2 - GlobalValues.WeightRef2;
                    for (int i = 0; i < FrontElecBalances.Count; i++)
                    {
                        sb.Append(string.Format("{0}:{1};  ", i + 1, FrontElecBalances[i].Weight));
                        if (FrontElecBalances[i].Weight > GlobalValues.FWeightEmptyLow)
                        {
                            results[i] = 1;
                            // InjectionMachine.WriteHaveBattery(i, 1, trayNum.ToString(), trayRow);
                            if (GlobalValues.EnableFrontInjectCheck == true)
                            {
                                if (!(FrontElecBalances[i].Weight >= min && FrontElecBalances[i].Weight <= max))
                                {
                                    results[i] = 2;
                                }
                            }
                        }
                        else
                        {
                            results[i] = 3;
                        }
                    }
                    for (int i = 0; i < 3; i++)
                    {
                        InjectionMachine.WriteFInjWeightOKNGs(results);
                    }
                    Messenger.Default.Send(sb.ToString(), "ReceiveEventInfo");
                    log.Info(string.Format("前称重量:{0}", sb.ToString()));
                    for (int i = 0; i < FrontElecBalances.Count; i++)
                    {
                        decimal fweight = FrontElecBalances[i].Weight;
                        if (fweight > GlobalValues.FWeightEmptyLow)
                        {
                            Count.INCount++;
                            var batt = new Weight();
                            batt.LineNo = GlobalValues.Line;
                            batt.ID = Guid.NewGuid();
                            batt.TrayCode = trayNum.ToString();
                            batt.RowNo = i < 16 ? trayRow : trayRow + 2;      //1-16第一行 17-32 第三行
                            batt.OrderNo = batt.Index = i + 1;
                            batt.FInjectionWeight = fweight;
                            batt.FWeightTime = DateTime.Now;
                            batt.Stage = 2;
                            batt.StdInj = GlobalValues.WeightRef1;
                            batt.InjWave = GlobalValues.WeightWave1;
                            batt.InjLow = GlobalValues.WeightRef1 - GlobalValues.WeightWave1;
                            batt.InjUp = GlobalValues.WeightRef1 + GlobalValues.WeightWave1;
                            batt.Flag = 0;
                            //前称重范围
                            var minWeight = GlobalValues.WeightRef2 - GlobalValues.WeightWave2;
                            var maxWeight = GlobalValues.WeightRef2 + GlobalValues.WeightWave2;
                            var range = string.Format("{0}~{1}", minWeight, maxWeight);
                            batt.Range = range;

                            //后称重范围
                            var weight = batt.FInjectionWeight + GlobalValues.WeightRef1;
                            var minBWeight = weight - GlobalValues.WeightWave1;
                            var maxBWeight = weight + GlobalValues.WeightWave1;
                            batt.Range2 = string.Format("{0}~{1}", minBWeight, maxBWeight);
                            //合格
                            batt.IsGoods = 100;
                            if (GlobalValues.EnableFrontInjectCheck == true)
                            {
                                var devVal1 = batt.FInjectionWeight - GlobalValues.WeightRef2;
                                var devVal2 = Math.Abs(Decimal.Parse(devVal1.ToString()));
                                if (devVal2 > GlobalValues.WeightWave2)
                                {
                                    if (devVal1 > 0)
                                    {
                                        //偏大
                                        batt.IsGoods = 1;
                                        batt.DevValue = devVal1;// - GlobalValues.WeightWave2;
                                    }
                                    else
                                    {
                                        //偏小
                                        batt.IsGoods = 2;
                                        batt.DevValue = devVal1; // + GlobalValues.WeightWave2;
                                    }
                                }
                            }
                            if(batt.IsGoods!=100)
                            {
                                Count.WeightNgCount++;
                                Count.NGCount++;
                            }
                            batt.ProductDate = DateTime.Now;
                            DB.AddBattryInfo(batt);
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                Messenger.Default.Send(ex.Message, "ReceiveEventInfo");
            }
            finally
            {
                for (int i = 0; i < 3; i++)
                {
                    InjectionMachine.WriteFInjectionWeightFin();
                    InjectionMachine.WriteFInjectionWeightClear();
                }
            }
        }

        //后扫码结果
        string BscanResult = "";
        /// <summary>
        /// 后扫描命令
        /// </summary>
        /// <param name="s"></param>
        void CmdBStartScan(string s)
        {
            try
            {
                BackScanner.StartScan();
                var scanResult = BackScanner.Receive();
                BscanResult = scanResult.Trim();
                if (!string.IsNullOrEmpty(BscanResult))
                {
                    var batt = DB.GetBattryByBarCode(BscanResult);
                    if (batt != null)
                    {
                        batt.BScanTime = DateTime.Now;
                        batt.ProductDate = DateTime.Now;
                        DB.UpdateBattryInfo(batt);
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }

        }
        /// <summary>
        /// 注液后称重
        /// </summary>
        /// <param name="s"></param>
        void CmdBInjectionWeight(string s)
        {
            try
            {
                var count = 0;
            Loop:
                var results = new ushort[32];
                var repairValues = new ushort[32];
                var trayNum = InjectionMachine.MW306;//后称重托架号
                var trayRow = InjectionMachine.MW307; //后称重托架行号
                var stationNo = InjectionMachine.MW230; //i注液站号
                var leakHuntingResults = InjectionMachine.GetLeakHuntingResult(); //测漏结果

           

                var leakHuntingResultsMsg = string.Format($"测漏结果 {string.Join(";", leakHuntingResults)}");
                log.Info(leakHuntingResultsMsg);
                Messenger.Default.Send(leakHuntingResultsMsg, "ReceiveEventInfo");


                var stationLayerNo = 0; //i注液站层号
                var batts1 = DB.GetBattryByTrayCodeTrayRow((short)trayNum, (short)trayRow);
                List<Weight> batts = new List<Weight>();
                if (batts1 != null)
                {
                    batts.AddRange(batts1);
                }
                Messenger.Default.Send("Count:" + batts.Count, "ReceiveEventInfo");
                log.Info("Count:" + batts.Count);
                if (batts == null || batts.Count == 0)
                {
                    var msg = string.Format("后称重托架号:{0} 行号:{1} 查找电池失败 将直接NG处理", trayNum, trayRow);
                    log.Info(msg);
                    Messenger.Default.Send(msg, "ReceiveEventInfo");
                    for (int i = 0; i < BackElecBalances.Count; i++)
                    {
                        results[i] = 6;
                    }
                }
                else
                {
                    if (batts.Count > 0)
                    {
                        if (BackElecBalances.Count > 0)
                        {
                            var sw = new Stopwatch();
                            sw.Start();
                            for (var i = 0; i < BackElecBalances.Count; i++)
                            {
                                BackElecBalances[i].startIndex = i;
                                BackElecBalances[i].IsWeightFin = false;
                                BackElecBalances[i].Weight = 0;
                                BackElecBalances[i].CurrWeight = 0;
                                BackElecBalances[i].IsRunning = false;
                                BackElecBalances[i].ServiceControl(true);
                            }
                            Thread.Sleep(500);
                            while (true)//等待称重完成或超时
                            {
                                if (BackElecBalances.Where(ss => ss.IsRunning && ss.IsWeightFin == false).ToList().Count > 0)
                                {
                                    foreach (var f in BackElecBalances)
                                    {
                                        if (sw.ElapsedMilliseconds > GlobalValues.WeightTimeout * 1000)
                                        {
                                            sw.Stop();
                                            f.Weight = f.CurrWeight;
                                            if (f.IsRunning == true && f.IsWeightFin == false)
                                            {
                                                var msg = string.Format("【后称重】{0}号称超时", f.startIndex);
                                                Messenger.Default.Send(msg, "ReceiveEventInfo");
                                                log.Error(msg);
                                            }
                                            f.IsWeightFin = true;
                                        }
                                        log.Info(String.Format("后称重>>> {0} {1} {2}", f.startIndex, f.Weight, f.CurrWeight));
                                        f.Weight = f.CurrWeight;
                                    }
                                    Thread.Sleep(50);
                                }
                                else
                                {
                                    foreach (var f in BackElecBalances)
                                    {
                                        f.Weight = f.CurrWeight;
                                        log.Info(String.Format("后称重>>> {0} {1} {2}", f.startIndex, f.Weight, f.CurrWeight));
                                    }
                                    break;
                                }
                            }

                            for (int i = 0; i < BackElecBalances.Count; i++)
                            {
                                var batt = batts.OrderByDescending(sss => sss.FWeightTime).Where(ss => ss.TrayCode == trayNum.ToString() && ss.RowNo == ((i < 16) ? trayRow : (trayRow + 2)) && ss.Index == (i + 1)).FirstOrDefault();
                                if (batt != null && BackElecBalances[i].Weight < GlobalValues.FWeightEmptyLow)
                                {
                                    log.Info(string.Format("后称 {0} {1} {2} ", i + 1, batt == null ? "null" : "have", BackElecBalances[i].Weight));
                                    //if (count < 1)
                                    //{
                                    //    count++;
                                    //    log.Info(string.Format("后称重有0值 重称1次"));
                                    //    goto Loop;
                                    //}
                                }
                            }
                            var sb = new StringBuilder();
                            for (int i = 0; i < BackElecBalances.Count; i++)
                            {
                                ushort result = 0;
                                var currWeight = BackElecBalances[i].Weight;
                                sb.Append(string.Format("{0}:{1};  ", i + 1, BackElecBalances[i].CurrWeight));
                                BackElecBalances[i].IsWeightFin = false;
                                var batt = batts.OrderByDescending(sss => sss.FWeightTime).Where(ss => ss.TrayCode == trayNum.ToString() && ss.RowNo == ((i < 16) ? trayRow : (trayRow + 2)) && ss.Index == (i + 1)).FirstOrDefault();
                                log.Info(string.Format("后称 {0} {1} {2}  ", i, batt == null ? "null" : "have", BackElecBalances[i].Weight));
                                if (batt != null)
                                {
                                    Count.OUTCount++;
                                    batt.OrderNo2 = i + 1;
                                    batt.Stage = 4;
                                    batt.BInjectionWeight = BackElecBalances[i].Weight;
                                    batt.BWeightTime = DateTime.Now;
                                    //实际注液量
                                    var diffValue = batt.BInjectionWeight - batt.FInjectionWeight;
                                    batt.InjectionWeight = diffValue;
                                    //最小值
                                    //var InjLow = GlobalValues.WeightRef1 - GlobalValues.WeightWave1;
                                    var InjLow = GlobalValues.WeightWave1Min;
                                    //最大值
                                    //var InjUp = GlobalValues.WeightRef1 + GlobalValues.WeightWave1;
                                    var InjUp = GlobalValues.WeightWave1Max;
                                    //补液量参考值
                                    var StdInj = GlobalValues.WeightRef1;
                                    batt.StationNo = stationNo;
                                    batt.LayerNo = stationNo;
                                    batt.LeakHuntingResult = leakHuntingResults[i];

                                    if (leakHuntingResults[i] != 1)
                                    {
                                        Count.LeakHuntingNgCount++;
                                    }

                                    if (diffValue >= GlobalValues.InjValueEmptyLow)//有注液
                                    {
                                        //判断注液值是否在范围内
                                        if (diffValue >= InjLow && diffValue <= InjUp)
                                        {
                                            if (GlobalValues.EnableBackInjectCheck == true)
                                            {
                                                var devVal3 = batt.BInjectionWeight - GlobalValues.WeightRef3;
                                                var devVal31 = System.Math.Abs(decimal.Parse(devVal3.ToString()));
                                                if (devVal31 < GlobalValues.WeightWave3)
                                                {
                                                    batt.IsGoods = 100; //OK  
                                                    result = 1;
                                                    // InjectionMachine.WriteBInjWeightOKNG(i, 1);
                                                }
                                                else
                                                {
                                                    batt.IsGoods = 3;//NG   
                                                    result = 3;
                                                    // InjectionMachine.WriteBInjWeightOKNG(i, 3);
                                                }
                                            }
                                            else
                                            {
                                                batt.IsGoods = 100; //OK  
                                                result = 1;
                                                // InjectionMachine.WriteBInjWeightOKNG(i, 1);
                                            }
                                            batt.Finished = true;
                                            batt.ProductDate = DateTime.Now;
                                        }
                                        else
                                        {
                                            //后称重NG 大于0传超重值 否则传补液量值
                                            if (batt.InjectionWeight > StdInj)
                                            {
                                                // batt.TheoryRepairValue = 0;
                                                batt.IsGoods = 3;//NG
                                                batt.Finished = true;
                                                log.Info("后称重NG信号 偏多");
                                                result = 3;
                                                //InjectionMachine.WriteBInjWeightOKNG(i, 3);
                                            }
                                            else
                                            {
                                                //补液值  
                                                batt.TheoryRepairValue = StdInj - batt.InjectionWeight;
                                                batt.Finished = true;
                                                batt.RepairFinished = false;
                                                batt.IsGoods = 4;//NG
                                                log.Info("后称重NG信号 偏少");
                                                //补液量
                                                repairValues[i] = (ushort)(batt.TheoryRepairValue * 10);
                                                result = 4;
                                            }
                                            batt.DevValue2 = batt.InjectionWeight - StdInj;

                                            batt.Finished = true;
                                            batt.ProductDate = DateTime.Now;

                                        }
                                        if (batt.IsGoods == 100)
                                        {
                                            
                                            Count.OKCount++;
                                            log.Info($"后称重OK数量+1：{Count.OKCount}");
                                        }
                                        else
                                        {
                                            Count.NGCount++;
                                            Count.WeightNgCount++;
                                            log.Info($"后称重NG数量+1：{Count.NGCount}------{Count.WeightNgCount}");
                                        }
                                            
                                    } //----
                                    else
                                    {
                                        batt.IsGoods = 5;
                                        batt.Finished = true;
                                        //补液量参考值减去实际注液量，得到差值
                                        batt.TheoryRepairValue = StdInj - batt.InjectionWeight;
                                        //补液量
                                        repairValues[i] = (ushort)Math.Ceiling((double)(batt.TheoryRepairValue * 10));
                                        //InjectionMachine.WriteBInjValue(i, (ushort)(batt.TheoryRepairValue * 10));
                                        result = 5;
                                        Count.NotInjCount++;
                                    }
                                    if (BackElecBalances[i].Weight <= GlobalValues.FWeightEmptyLow)//前称重量异常
                                    {
                                        result = 7;
                                    }

                                    if (BDB.AddBattryInfo(batt))
                                    {
                                        var msg11 = string.Format("后称保存成功 {0} {1} {2}", trayNum, ((i < 16) ? trayRow : (trayRow + 2)), (i + 1));
                                        Messenger.Default.Send(msg11, "ReceiveEventInfo");
                                        log.Info(msg11);
                                        DB.DeleteBattryInfo(batt.ID);//从Weight删除 
                                        //上传MES/////////////////
                                        if (InfoDataModel.Tmp.EnbleMesOnOff)
                                        {
                                            Task.Factory.StartNew(() =>
                                            {
                                               
                                                //工艺参数上传
                                                var Int_result = InjectMes.MESProductUpLoad(batt,Count);
                                             
                                                //与MES标准工艺参数对比
                                                InjectMes.CompareStandardProcess(batt);
                                                var msgmes = string.Format($"MES上传:{trayNum},{((i < 16) ? trayRow : (trayRow + 2))},{(Int_result == 1 ? "成功" : $"失败")}");
                                                Messenger.Default.Send(msgmes, "ReceiveEventInfo");
                                                log.Info(msgmes);
                                               
                                            },TaskCreationOptions.LongRunning);
     
                                        }
                                        //////////////////////////
                                    }
                                    else
                                    {
                                        var msg11 = string.Format("后称保存失败 {0} {1} {2}", trayNum, ((i < 16) ? trayRow : (trayRow + 2)), (i + 1));
                                        Messenger.Default.Send(msg11, "ReceiveEventInfo");
                                        log.Info(msg11);
                                    }
                                    Messenger.Default.Send(batt, "UpdateBBattryInfoToUI");

                                }
                                else
                                { //1 OK,  3多 4少 5没注 6没找到 7没电池
                                    if (BackElecBalances[i].Weight <= GlobalValues.FWeightEmptyLow)//前称重量异常
                                    {
                                        result = 7;
                                    }
                                    else
                                    {
                                        result = 6;
                                    }
                                }
                                results[i] = result;


                            }
                            Messenger.Default.Send(string.Format("后称重量:{0}", sb.ToString()), "ReceiveEventInfo");
                            log.Info(string.Format("后称重量:{0}", sb.ToString()));
                        }
                    }
                }

                for (int i = 0; i < 3; i++)
                {
                    //写入后称重结果
                    InjectionMachine.WriteBInjWeightOKNGs(results);
                    //写补液量
                    InjectionMachine.WriteBInjWeightRepairValues(repairValues);
                }
                BscanResult = "";
            }
            catch (Exception ex)
            {
                log.Error(ex.ToString());
            }
            finally
            {
                for (int i = 0; i < 3; i++)
                {
                    InjectionMachine.WriteBInjectionWeightFin();
                    InjectionMachine.WriteBInjectionWeightClear();
                }
            }
        }

        /// <summary>
        /// 注液前称重清零
        /// </summary>
        /// <param name="s"></param>
        void CmdBInjectionWeightClear(string s)
        {
            try
            {
                if (FrontElecBalances.Count > 0)
                {
                    Parallel.ForEach(FrontElecBalances, (ss) =>
                    {
                        ss.ClearZero();
                    });
                }
                Thread.Sleep(1000);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
            finally
            {
                InjectionMachine.WriteFWeightFin();
                InjectionMachine.WriteFWeightClear();
            }
        }
        /// <summary>
        /// 注液后称重清零
        /// </summary>
        /// <param name="s"></param>
        void CmdAInjectionWeightClear(string s)
        {
            try
            {
                if (BackElecBalances.Count > 0)
                {
                    Parallel.ForEach(BackElecBalances, (ss) =>
                    {
                        ss.ClearZero();
                    });
                }
                Thread.Sleep(1000);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
            finally
            {
                InjectionMachine.WriteBWeightFin();
                InjectionMachine.WriteBWeightClear();
            }
        }
        /// <summary>
        /// 补液称重清零
        /// </summary>
        /// <param name="s"></param>
        void CmdRInjectionWeightClear(string s)
        {
            try
            {
                if (BackElecBalances.Count > 0)
                {
                    foreach (var reb in RepairElecBalances)
                    {
                        reb.ClearZero();
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }
        #endregion
    }
}
